﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BCMS.Business.DataContract;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.IO;

namespace BCMS.Setup
{
    public partial class frmUserInit : Form
    {
        public frmUserInit()
        {
            this.Font = SystemFonts.MessageBoxFont;
            InitializeComponent();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                btnOK.Enabled = false;
                lblCSDL.Text = btnCreateDB();
                if (lblCSDL.Text.Equals("OK"))
                    lblCSDL.ForeColor = Color.Green;
                else
                    lblCSDL.ForeColor = Color.Red;

                lblTables.Text = restoreDb();
                if (lblTables.Text.Equals("OK"))
                    lblTables.ForeColor = Color.Green;
                else
                    lblTables.ForeColor = Color.Red;

                lblAdmin.Text = createAdmin();
                if (lblAdmin.Text.Equals("OK"))
                    lblAdmin.ForeColor = Color.Green;
                else
                    lblAdmin.ForeColor = Color.Red;
                btnOK.Enabled = true;

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        public string restoreDb()
        {
            string host = txtServer.Text;
            string dbname = txtDb.Text;
            string script = txtScript.Text;
            string user = txtUser.Text;
            string pass = txtPass.Text;
            string pathExec = txtPath.Text;

            try
            {
                ProcessStartInfo pInfo = new ProcessStartInfo("cmd.exe", "/C \"" +
                                                pathExec + "\" -u " +
                                                user + " -h " +
                                                host + " --password=" +
                                                pass + " " +
                                                dbname + " < " + script);
                pInfo.CreateNoWindow = true;
                pInfo.UseShellExecute = false;
                pInfo.RedirectStandardOutput = true;
                pInfo.RedirectStandardError = true;
                Process process = Process.Start(pInfo);
                string output = process.StandardError.ReadToEnd();

                process.WaitForExit();
                process.Close();
                return "OK";
            }
            catch
            {
                return "ERROR";
            }
        }

        private void btnFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "SQL File|*.sql";
            dlg.Title = "Select script file";
            dlg.InitialDirectory = Application.StartupPath;
            if (dlg.ShowDialog() == DialogResult.OK)
                txtScript.Text = dlg.FileName;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "SQL.exe |mysql.exe";
            dlg.Title = "Select mysql.exe file";
            dlg.InitialDirectory = Application.StartupPath;
            if (dlg.ShowDialog() == DialogResult.OK)
                txtPath.Text = dlg.FileName;
        }

        string btnCreateDB()
        {
            try
            {
                StringBuilder cnn = new StringBuilder();
                cnn.Append("server=" + txtServer.Text + ";");
                cnn.Append("uid=" + txtUser.Text + ";");
                cnn.Append("pwd=" + txtPass.Text + ";");

                MySqlConnection conn = new MySqlConnection(cnn.ToString());
                MySqlCommand cmd = new MySqlCommand("CREATE DATABASE IF NOT EXISTS " +
                                                        txtDb.Text + ";", conn);

                conn.Open();
                cmd.ExecuteNonQuery();
                conn.Close();
                return "OK";
            }
            catch (System.Exception e)
            {
                return "ERROR: " + e.Message;
            }
        }

        string createAdmin()
        {
            try
            {
                StringBuilder cnn = new StringBuilder();
                cnn.Append("server=" + txtServer.Text + ";");
                cnn.Append("uid=" + txtUser.Text + ";");
                cnn.Append("pwd=" + txtPass.Text + ";");
                cnn.Append("database=" + txtDb.Text + ";");


                MySqlConnection conn = new MySqlConnection();
                conn.ConnectionString = cnn.ToString();
                conn.Open();

                UserInfo user = new UserInfo();
                user.UserName = txtUserName.Text;
                user.Password = txtPassword.Text;
                user.Roles = "1111";

                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "INSERT INTO users (USERNAME, PASSWORD, ROLES, FULLNAME, EMAIL, PHONE, ADDRESS, POSITION, DEPARTMENT) VALUES (@USERNAME, MD5(@PASSWORD), @ROLES, @FULLNAME, @EMAIL, @PHONE, @ADDRESS, @POSITION, @DEPARTMENT)";
                cmd.Prepare();

                cmd.Parameters.AddWithValue("@USERNAME", user.UserName);
                cmd.Parameters.AddWithValue("@PASSWORD", user.Password);
                cmd.Parameters.AddWithValue("@ROLES", user.Roles);
                cmd.Parameters.AddWithValue("@FULLNAME", string.Empty);
                cmd.Parameters.AddWithValue("@EMAIL", string.Empty);
                cmd.Parameters.AddWithValue("@PHONE", string.Empty);
                cmd.Parameters.AddWithValue("@ADDRESS", string.Empty);
                cmd.Parameters.AddWithValue("@POSITION", string.Empty);
                cmd.Parameters.AddWithValue("@DEPARTMENT", string.Empty);

                cmd.ExecuteNonQuery();
                return "OK";
            }
            catch (System.Exception e)
            {
                return "ERROR: " + e.Message;
            }

        }

        void runScript(string cnnStr, string file)
        {
            MySqlConnection conn = new MySqlConnection(cnnStr);
            conn.Open();
            MySqlCommand _cmd = conn.CreateCommand();
            StreamReader _streamReader = null;
            string _myQuery = string.Empty;
            int _rc = 0;

            try
            {
                _streamReader = new
                StreamReader(file);

                _myQuery = _streamReader.ReadToEnd();
                _cmd.CommandType = CommandType.Text;
                _cmd.CommandText = _myQuery;
                _rc = _cmd.ExecuteNonQuery();
                MessageBox.Show("Done!");
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
                return;
            }
            finally
            {
                if (_streamReader != null)
                    _streamReader.Close();
            }
        }
    }
}
